#include "polynomial.h"

Polynomial::Polynomial(string strPolyn){	
	int nxtTerm=0;
	PolyTerm *pt;
	error_num=0;
	for(int i=0;i<strPolyn.length();){
		int signc=1,signe=1;
		double c=1,e=0;
		
		if(strPolyn[i]=='-'){
			signc=-1;
			i++;
		}
		else if(strPolyn[i]=='+') i++;
//read polynomial term		
		while(!nxtTerm&&i<strPolyn.length()){
			while(strPolyn[i]==' ')i++;//ignore whitespace
			if(strPolyn[i]=='+'||strPolyn[i]=='-'){nxtTerm=-1; goto end_while;}
			if(is_num(strPolyn[i])) c=read_num(strPolyn,&i);
			else if(is_var(strPolyn[i])){
				i++;
				if(i>=strPolyn.length()){e=1;nxtTerm=-1;goto end_while;}
				else if(strPolyn[i]=='+'||strPolyn[i]=='-'){e=1; nxtTerm=-1;}
			}
			else if(strPolyn[i]=='^'){
				i++;
				while(strPolyn[i]==' ')i++;//ignore whitespace
				if(is_num(strPolyn[i])){
					e=read_num(strPolyn,&i);
					if(trunc(e)!=e){
						error_num=1;
						error="Polynomials do not have rational exponents, but we will do it anyway.";
					}
				}
				else if(strPolyn[i]=='-'){
					i++;
					e=-1*read_num(strPolyn,&i);
					error_num=1;
					error="Polynomials don't have negative exponents, but we will do it anyway.";
				}	//not a polynomial
				else {
					error_num=-1;
					error="There is an error in your polynomial string";
					goto end_for;
				}
		  }
		}
		end_while:

		//pt.set_coef(c*signc);pt.set_exp(e*signe);
		pt=new PolyTerm(c*signc,e*signe);

		Terms.push_back(*pt);
		
	//	

		nxtTerm=0;
	}
end_for:
	if(error_num==-1)Terms.clear();	
}

Polynomial::~Polynomial(){
	Terms.clear();
}

double Polynomial::read_num(string s, int *i){
	double num=0,den=1,sign=1;
	
	if(s[*i]=='-'){sign=-1;(*i)++;}
	
	num=atof(s.substr(*i,s.length()).c_str());
	
	while(is_num(s[*i])&&(*i)<s.length())(*i)++;
	
	if(s[*i]=='/'){
		(*i)++;
		den=atof(s.substr(*i,s.length()).c_str());
	}
	
	while(is_num(s[*i])&&(*i)<s.length()) (*i)++;
	
	return sign*num/den;
}

string Polynomial::print(){
	string s("Polynomial:");
	//cout<<Terms.size();
	if(Terms.size()==0) s="There is no polynomial";
	for(int i=0;i<Terms.size();i++){
		if(Terms[i].get_coef()>0&&i!=0) s+="+";
		if(Terms[i].get_exp()==0){s+=ToString(Terms[i].get_coef());}
		else{ 
		 	if(Terms[i].get_coef()==1)	s+="x";
		 	else if(Terms[i].get_coef()==-1) s+="-x";
		 	else s+=ToString(Terms[i].get_coef())+"x";
			
			if(Terms[i].get_exp()!=1) s+="^"+ToString(Terms[i].get_exp());
		}
	}
	return s;
}

double	Polynomial::eval(double x){
	double result=0;
	for(int i=0;i<Terms.size();i++){
		result+=Terms[i].get_coef()*pow(x,Terms[i].get_exp());
	}
	
	return result;
}

dcmpx	Polynomial::eval(dcmpx x){
	dcmpx result=(0,0);
	for(int i=0;i<Terms.size();i++){
		result+=dcmpx(Terms[i].get_coef())*pow(x,Terms[i].get_exp());
	}
	
	return result;
}

/*
If we are looking at the first term, we dont care whether or not it is positive or negative....
If i=0 
	if coef(0)=1 print x
	if coef(0)=-1 print -x
then print exp(0)
*/
